package com.piaoniu.open.http;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.config.SocketConfig;
import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
import org.apache.http.impl.client.HttpClientBuilder;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

//todo 现在client 实现是绑死的，后续是否需要给客户端选择实现可能性
@Slf4j
public class PnHttpClient {

    private HttpClient httpClient;

    private PnHttpClient() {

    }

    public PnHttpClient(HttpProperties httpProperties) {
        httpClient = HttpClientBuilder.create()
                .setDefaultSocketConfig(SocketConfig.custom().setSoKeepAlive(false).setTcpNoDelay(true).build())
                .setDefaultRequestConfig(
                        RequestConfig.custom()
                                .setConnectionRequestTimeout(httpProperties.getConnectTimeout())
                                .setConnectTimeout(httpProperties.getConnectTimeout())
                                .setSocketTimeout(httpProperties.getReadTimeout()).build())
                .setRetryHandler(new DefaultHttpRequestRetryHandler(httpProperties.getRetry(), true))
                .build();
    }


    public ResponseObject execute(HttpUriRequest request) throws IOException {
        return httpClient.execute(request, httpResponse -> {
            if (httpResponse.getEntity() != null && httpResponse.getEntity().getContent() != null) {
                StatusLine statusLine = httpResponse.getStatusLine();
                if(statusLine.getStatusCode()!=200){
                    log.warn("http fail ,message : {}", statusLine.getReasonPhrase());
                }
                String responseBody = IOUtils.toString(httpResponse.getEntity().getContent(), StandardCharsets.UTF_8);
                return new ResponseObject(statusLine.getStatusCode(), responseBody);
            }
            return new ResponseObject(httpResponse.getStatusLine().getStatusCode(), "http 响应错误!");
        });
    }

}
